package com.errol.batchprocessor.employeeaddition.advisorimpl.demand;

import com.renjia.dao.*;
import com.renjia.entity.BusDemandEmployeeTemp;
import com.renjia.entity.CoreEmployeeImportBatch;
import com.renjia.enums.DemandEmployeeFailTypeEnum;
import com.renjia.enums.DemandEmployeeStatusEnum;
import com.renjia.enums.DemandEmployeeTypeEnum;
import com.renjia.enums.DemandLastEmployeeBatchStatusEnum;
import com.renjia.pojo.AutoCompleteFlagParser;
import com.renjia.service.CoreEmployeeImportBatchService;
import com.renjia.service.generic.log.LogService;
import com.renjia.service.generic.middleware.batchprocessor.payload.AbstractBatchPayload;
import com.renjia.service.generic.support.customer.CustomerChannelSupportService;
import com.renjia.service.generic.support.employee.BankCardSupportService;
import com.renjia.service.generic.support.employee.EmployeeCustomerSupportService;
import com.renjia.service.generic.support.employee.EmployeeSupportService;
import com.renjia.service.integration.threeelements.ThreeElementsService;
import com.renjia.service.module.employee.AgreementSigningService;
import com.renjia.service.module.employeeaddition.advisorimpl.EmployeeAdvisorTypeEnum;
import com.renjia.service.module.employeeaddition.advisorimpl.common.ThreeElementForceHandler;
import com.renjia.service.module.employeeaddition.advisorimpl.demand.payload.DemandEmployeeBatchPayload;
import com.renjia.service.module.employeeaddition.advisorimpl.demand.payload.DemandEmployeePiecePayload;
import com.renjia.service.module.employeeaddition.advisorimpl.demand.payload.DemandEmployeeSinglePayload;
import com.renjia.service.module.messagecenter.MsgCenterSendService;
import com.renjia.util.EpayCallingService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

/**
 * 接单导入管理（新增或编辑）的扩展，只有 Single 系列扩展点会触发
 *
 * @author zhang xiao bin
 * @version v1.0
 * @date 2021/03/10
 * @since v5.0.6
 **/
@Service
public class DemandEmployeeManageAdvisorImpl extends DemandEmployeeAdvisorImpl
        implements ThreeElementForceHandler<Object, BusDemandEmployeeTemp, DemandEmployeeBatchPayload, DemandEmployeePiecePayload, DemandEmployeeSinglePayload, DemandEmployeeManageAdvisorImpl> {

    public DemandEmployeeManageAdvisorImpl(CoreEmployeeImportBatchService coreEmployeeImportBatchService,
                                           CoreEmployeeMapper coreEmployeeMapper, CoreEmployeeCustomerMapper coreEmployeeCustomerMapper,
                                           CoreUserBankMapper coreUserBankMapper, CoreAgreementDetailMapper coreAgreementDetailMapper, ThreeElementsService threeElementsService,
                                           EmployeeSupportService employeeSupportService, EmployeeCustomerSupportService employeeCustomerSupportService,
                                           BankCardSupportService bankCardSupportService, CustomerChannelSupportService customerChannelSupportService,
                                           AgreementSigningService agreementSigningService, EpayCallingService epayCallingService, LogService logService,
                                           BusDemandMapper busDemandMapper,
                                           BusDemandEmployeeMapper busDemandEmployeeMapper,
                                           BusDemandEmployeeTempMapper busDemandEmployeeTempMapper,
                                           MsgCenterSendService msgCenterSendService) {
        super(coreEmployeeImportBatchService, coreEmployeeMapper, coreEmployeeCustomerMapper, coreUserBankMapper, coreAgreementDetailMapper, threeElementsService,
                employeeSupportService, employeeCustomerSupportService, bankCardSupportService, customerChannelSupportService, agreementSigningService,
                epayCallingService, logService, busDemandMapper, busDemandEmployeeMapper, busDemandEmployeeTempMapper, msgCenterSendService);
    }

    @Override
    public boolean shallProcess(@NonNull AbstractBatchPayload<CoreEmployeeImportBatch, EmployeeAdvisorTypeEnum, Object, BusDemandEmployeeTemp> advisorPayload) {
        return EmployeeAdvisorTypeEnum.DEMAND_EMPLOYEE_MANAGE == advisorPayload.getAdvisorTypeEnum();
    }

    @Override
    public boolean doPrepareOnSingleStart(@NonNull DemandEmployeeSinglePayload singlePayload, @NonNull DemandEmployeePiecePayload piecePayload, @NonNull DemandEmployeeBatchPayload batchPayload) {
        // 允许重复验证，除了单条数据也需要做的准备
        prepareForDuplicationCheckOfDocument(batchPayload);
        piecePayload.prepareValidator();
        return true;
    }

    @Override
    protected boolean dealWithCoreEmployee(DemandEmployeeSinglePayload singlePayload, DemandEmployeePiecePayload piecePayload, DemandEmployeeBatchPayload batchPayload) {
        if (super.dealWithCoreEmployee(singlePayload, piecePayload, batchPayload)) {
            return true;
        } else if (Boolean.FALSE.equals(singlePayload.getIsThreeElementSuccess())) {
            // 新增用户时，三要素失败，且满足一定次数，强制认证通过，并添加标识
            if (forceReviewCoreEmployee(singlePayload, piecePayload, batchPayload, this)) {
                return super.dealWithCoreEmployee(singlePayload, piecePayload, batchPayload);
            } else {
                // 强制验证通过失败
                return false;
            }
        } else {
            // 其他验证失败
            return false;
        }
    }

    @Override
    protected boolean dealWithCoreUserBank(DemandEmployeeSinglePayload singlePayload, DemandEmployeePiecePayload piecePayload, DemandEmployeeBatchPayload batchPayload) {
        super.dealWithCoreUserBank(singlePayload, piecePayload, batchPayload);
        return forceReviewUserBank(singlePayload, piecePayload, batchPayload, this);
    }

    @Override
    protected void updateValidateSuccess(DemandEmployeeSinglePayload singlePayload, DemandEmployeePiecePayload piecePayload, DemandEmployeeBatchPayload batchPayload) {
        if (singlePayload.getDemandEmployeeFailTypeEnum() == DemandEmployeeFailTypeEnum.IMPORT_REPEAT) {
            // 编辑只要是有重复，就失败
            singlePayload.getErrMsgList().add("该用户已有任务邀约");
        } else {
            singlePayload.getSingleEntity().setEmployeeId(singlePayload.getCoreEmployee().getId());
            if (StringUtils.isNotEmpty(singlePayload.getSingleEntity().getId())) {
                // 编辑临时表，所有字段都可以编辑，更新整条记录
                singlePayload.getSingleEntity().setUpdateUser(batchPayload.getCoreUser());
                singlePayload.getSingleEntity().setFailReason("");
                singlePayload.getSingleEntity().setRecordStatus(DemandEmployeeTypeEnum.ASSIGN.getCode().equals(singlePayload.getSingleEntity().getRecordType())
                        ? DemandEmployeeStatusEnum.ACCEPTED.getCode() : DemandEmployeeStatusEnum.UN_CONFIRMED.getCode());
                // 编辑时检查自动补全的信息是否被编辑
                if (singlePayload.getSingleEntity().getAutoCompleteFlag() != null && singlePayload.getSingleEntity().getAutoCompleteFlag() > 0) {
                    BusDemandEmployeeTemp oldDemandEmployeeTemp = this.getOldDemandEmployeeTemp(singlePayload);
                    singlePayload.getSingleEntity().setAutoCompleteFlag(this.checkAutoComplete(singlePayload, new AutoCompleteFlagParser(singlePayload.getSingleEntity().getAutoCompleteFlag()),
                            oldDemandEmployeeTemp.getBankCard(), oldDemandEmployeeTemp.getMobile()).getAutoCompleteFlag());
                }
                busDemandEmployeeTempMapper.updateById(singlePayload.getSingleEntity());
            } else {
                // 手动添加接单，校验通过且非重复导入，加入接单表，同时检查导入中批次有无重复导入
                singlePayload.getSingleEntity().setCreateAndUpdateUser(batchPayload.getCoreUser());
                busDemandEmployeeMapper.insert(singlePayload.getSingleEntity());
                if (DemandLastEmployeeBatchStatusEnum.WAITING_CONFIRM.getCode().equals(batchPayload.getBusDemand().getLastEmployeeBatchStatus())) {
                    // 导入接单和编辑接单，busDemand 都有，正在导入的批次中相同 employeeId 的记录更新 failType
                    busDemandEmployeeTempMapper.updateFailTypeByBatchNo(singlePayload.getCoreEmployee().getId(),
                            batchPayload.getBusDemand().getLastEmployeeBatchNo(), DemandEmployeeFailTypeEnum.IMPORT_REPEAT.getCode());
                }
            }
        }
    }

    @Override
    protected void updateValidateFailed(DemandEmployeeSinglePayload singlePayload, DemandEmployeePiecePayload piecePayload, DemandEmployeeBatchPayload batchPayload, String errMsg) {
        // 无论是编辑导入失败的记录，还是手动添加，验证失败的话，都不保存
    }

    @Override
    public boolean doCleanUpOnBatchPost(@NonNull DemandEmployeeBatchPayload batchPayload) {
        return true;
    }

    private BusDemandEmployeeTemp getOldDemandEmployeeTemp(DemandEmployeeSinglePayload singlePayload) {
        BusDemandEmployeeTemp oldSingleEntity = singlePayload.getOldSingleEntity();
        if (oldSingleEntity == null) {
            oldSingleEntity = busDemandEmployeeTempMapper.selectById(singlePayload.getSingleEntity().getId());
            singlePayload.setOldSingleEntity(oldSingleEntity);
        }
        return oldSingleEntity;
    }
}
